#/usr/bin/env python3
import os
from enum import Enum
class HttpCode(Enum):
    Code200 = 200

class HttpProtocol:
    res_dict = {} #(content_type, response_head)
    def __init__(self, conf = None):
        if conf:
            self.error_page = conf.get("error_page")
        self.res_dict["ico"] = ("image/x-icon", ['Accept-Ranges: bytes'])
        self.res_dict["png"] = ("image/png", ['Accept-Ranges: bytes'])
        self.res_dict["gif"] = ("image/gif", ['Accept-Ranges: bytes'])
        self.res_dict["svg"] = ("image/svg+xml", [])
        #audio
        self.res_dict["mp3"] = ("audio/mpeg", ['Content-Range: bytes '])
        #media
        self.res_dict["mp4"] = ("video/mp4", ['Accept-Ranges:bytes', 'Content-Range: bytes '])
        #document
        self.res_dict["js"] = ("application/javascript; charset=utf-8", ['Accept-Ranges: bytes'])
        self.res_dict["css"] = ("text/css", ['Accept-Ranges: bytes'])
        self.res_dict["text"] = ("text/html", [])

        self.xuchuan = ["mp4"]

    def get_header(self, http_code, res_type, file_size, content_len, range_start = -1, range_end = -1):
        if res_type not in self.res_dict:
            res_type = "text"
        content_type = self.res_dict[res_type][0]
        header = 'HTTP/1.1 '
        if res_type in self.xuchuan:
            header = header + '206 Partial Content\n'
        else:
            header = header + str(http_code) + ' Found\n'
        header += 'Server: pytinyserver\n'
        header += 'Content-type: ' + content_type + '\n'
        header_lines = self.res_dict[res_type][1]
        for res_header in header_lines:
            if res_header != '':
                if "Content-Range" in res_header and (range_start != -1):
                    header += res_header + str(range_start)+"-"+str(range_end)+"/"+str(file_size)+'\n'
                    header += 'Content-Length: '+str(range_end-range_start+1) + "\n"
                elif "Content-Range" in res_header:
                    header += res_header + "0-"+str(content_len-1)+"/"+str(file_size)+'\n'
                else:
                    header += res_header + '\n'
        header += 'Content-Length: '+str(content_len) + "\n"
        header += "\r\n"
        #print("response head:", header)
        return header

    def get_static_content(self, file_name, file_range = (-1, -1)):
        suffix = file_name[file_name.rfind(".")+1:]
        content = None
        start_pos, end_pos = file_range
        file_size = os.path.getsize(file_name)
        with open(file_name, "rb") as rf:
            if start_pos != -1:
                rf.seek(start_pos)
            if end_pos != -1 and end_pos > start_pos:
                content = rf.read(end_pos - start_pos + 1)
            else:
                content = rf.read()
        content_len = len(content)
        if start_pos!= -1 and end_pos == -1:
            end_pos = len(content) + start_pos - 1
        print(file_name, suffix, content_len, start_pos, end_pos)
        if suffix in self.res_dict:
            head = self.get_header(200, suffix, file_size, content_len, start_pos, end_pos)
        else:
            head = self.get_header(200, "text", file_size, content_len)
        response_content = head.encode("utf-8") + content
        return response_content


    def get_content(self):
        content = '''<html><head>test</head><body>relocation to internal address</body></html>'''
        response_content = self.get_header(302, "text", len(content), len(content)) + "\n" + content
        return response_content

    def get_error_page(self):
        print("get error page")
        content = '''<html><titile>error</titile><body>server error</body></html>'''
        response_content = self.get_header(200, "html", len(content), len(content)) + "\n" + content
        return response_content.encode()

